package com.shn.ClientService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;

import cn.hutool.core.collection.CollUtil;
import reactor.core.publisher.Mono;

public class VersionLoadBalancerClient implements ReactorServiceInstanceLoadBalancer {

	@Resource
	ConfigUtils configUtils;

	private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

	public VersionLoadBalancerClient(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider) {
		this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
	}

	@Override
	public Mono<Response<ServiceInstance>> choose(Request request) {
		ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider
				.getIfAvailable(NoopServiceInstanceListSupplier::new);

		return supplier.get().next().map(list -> getInstanceResponse(list, configUtils.getVersion()));

	}

	private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances, String versionValue) {
		// 根据版本信息进行过滤
		List<ServiceInstance> chooseInstances = new ArrayList<>();
		for (int i = 0; i < instances.size(); i++) {
			ServiceInstance serInst = instances.get(i);
			HashMap<String, String> map = (HashMap<String, String>) serInst.getMetadata();
			if (versionValue.equals(map.get("version"))) {
				chooseInstances.add(serInst);
			}
		}

		if (CollUtil.isEmpty(chooseInstances)) {
			System.out.println("没有满足版本为:" + versionValue + "的服务实例列表，直接使用所有服务实例列表");
			chooseInstances = instances;
		}

		// 通过随机算法实现负载均衡
		int size = chooseInstances.size();
		Random random = new Random();
		ServiceInstance instance = chooseInstances.get(random.nextInt(size));
		return new DefaultResponse((ServiceInstance) instance);

	}

}
